#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <math.h>
#define DEBUG 0

using namespace std;

long getLimit(long n)
{
    long p;
    for(p = 0; n >= pow(10,p); p++);
    return (long)pow(10,p);
}

string ltos(long n)
{
    stringstream ss;
    string str;
    ss << n;
    ss >> str;
    return str;
}

long stol(string s)
{
    stringstream ss;
    long n;
    ss << s;
    ss >> n;
    return n;
}

int isPrime(long n)
{
    if(n == 2) return 1;
    if(n % 2 == 0) return 0;
    long limit = (long)sqrt(n);
    for(long i = 3; i <= limit; i+=2)
      if(n % i == 0)
        return 0;
    if(n >= 3) return 1;
    else return 0;
}

int checkIfPermutationsArePrimes(string sin, string sout)
{
    if(sin.size() == 1)
    {
       if(isPrime(stol(sout + sin)))
           return 1;
       else
           return 0;
    }
    
    int r;
    for(int i = 0; i < sin.size(); i++)
    {
         r = checkIfPermutationsArePrimes(
                        sin.substr(0,i) + sin.substr(i+1),
                        sout + sin[i]
                        );
         if(r == 0)
             return 0;
    }
    return 1;
}

int isAnagrammaticPrime(string s)
{
    for(int i = 0; i < s.size(); i++)
        if(stol(s.substr(i,1)) % 2 == 0) return 0;
    
    if(!isPrime(stol(s))) return 0;
    
    return checkIfPermutationsArePrimes(s, "");
    
    return 1;
}

int main ()
{
    long n;
    long limit;
    long anagrammaticprime;
    long lcandidate;
    string scandidate;
    
    while(true)
    {
        cin>>n;
        if(n == 0) break;
        anagrammaticprime = 0;
        limit = getLimit(n);
        n++;

        if(DEBUG) cout<<"limit = "<<limit<<endl;
        
        if(n <= 2)
        {
            if(DEBUG)  cout<<endl<<"candidate = "<<2<<endl;
            anagrammaticprime = 2;
        }
        else if(n >= 1000) ///al parecer no existen primos anagramaticos entre 1000 y 10000000...
            anagrammaticprime = 0;
        else
        {
            if(n % 2 == 0) n++;
            for(lcandidate = n; lcandidate < limit; lcandidate += 2)
            {
                scandidate = ltos(lcandidate);
                if(DEBUG) cout<<endl<<"candidate = "<<lcandidate<<endl;
                if(isAnagrammaticPrime(scandidate))
                {
                    anagrammaticprime = lcandidate;
                    break;
                }
            }
        }
        cout<<anagrammaticprime<<endl;
    }
    return 0;
}
